<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>封装 AJAX 请求</title>
</head>
<body>
    <script>
        //声明对象
        const $ = {
            get: function(url, data, callback, type){
                //发送 AJAX 请求
                const xhr = new XMLHttpRequest();
                //判断
                if(type === 'json'){
                    xhr.responseType = 'json';
                }
                //对 data 对象进行字符串转换  {id:100, vip: 9} => id=100&vip=9
                let str = '';
                for(let i in data){
                    str += `${i}=${data[i]}&`;
                }
                str = str.slice(0, -1);
                //初始化
                xhr.open('GET', url+'?'+str);
                //发送 
                xhr.send();
                //处理结果
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        if(xhr.status >= 200 && xhr.status < 300){
                            //处理响应结果
                            callback(xhr.response);
                        }
                    }
                }
            }
        }

        $.get('http://127.0.0.1/json-server', {id:100, vip: 9}, function(data){
            console.log(data);
        },'json');
    </script>
</body>
</html>